/**
 * 
 */
package com.treehouse.northlight.system;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.physics.box2d.Transform;
import com.treehouse.northlight.component.SpriteWrapper;
import com.treehouse.northlight.component.TransformWrapper;

/**
 * System Class.
 * 
 * Takes care of the sprite rendering logic.
 * 
 * @author Julian Biermann
 * @version 1.0 03.03.2013
 * 
 */
public class SpriteRenderSystem extends EntityProcessingSystem {

	private SpriteBatch batch;

	private Camera camera;

	private ComponentMapper<SpriteWrapper> spriteMapper;
	private ComponentMapper<TransformWrapper> transformMapper;

	/**
	 * Constructor
	 * 
	 */
	@SuppressWarnings("unchecked")
	public SpriteRenderSystem(SpriteBatch batch, Camera camera) {
		super(Aspect.getAspectForAll(SpriteWrapper.class,
				TransformWrapper.class));
		this.batch = batch;
		this.camera = camera;
	}

	/**
	 * @see com.artemis.EntitySystem#initialize()
	 */
	@Override
	protected void initialize() {
		this.spriteMapper = world.getMapper(SpriteWrapper.class);
		this.transformMapper = world.getMapper(TransformWrapper.class);
	}

	/**
	 * @see com.artemis.EntitySystem#begin()
	 */
	@Override
	protected void begin() {
		Gdx.gl.glClearColor(0f, 0.6f, 1.0f, 1f);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

		this.camera.update();
		this.batch.setProjectionMatrix(this.camera.combined);
		this.batch.begin();
	}

	/**
	 * @see com.artemis.systems.EntityProcessingSystem#process(com.artemis.Entity)
	 */
	@Override
	protected void process(Entity e) {
		Sprite sprite = this.spriteMapper.get(e).getSprite();
		Transform transform = this.transformMapper.get(e).getTransform();

		sprite.setPosition(transform.getPosition().x, transform.getPosition().y);
		sprite.setRotation(transform.getRotation());

		sprite.draw(this.batch);
	}

	/**
	 * @see com.artemis.EntitySystem#end()
	 */
	@Override
	protected void end() {
		this.batch.end();
	}

	/**
	 * @see com.artemis.systems.EntityProcessingSystem#checkProcessing()
	 */
	@Override
	protected boolean checkProcessing() {
		return true;
	}
}
